/**
 * Vision Analyzer Application
 *
 * 重构后的应用程序核心类，将index.js的复杂逻辑封装成可测试的组件
 */

const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const {
    CallToolRequestSchema,
    ListToolsRequestSchema,
} = require('@modelcontextprotocol/sdk/types.js');
const path = require('path');

const visionAnalyzer = require('../../analyze.js');
const { checkJsonConfiguration, showConfigurationSuccess } = require('../../config-checker');
const ConfigManager = require('../../config-manager');
const WebConfigServer = require('../../web-config-server');
const { createTextResponse, createJsonResponse } = require('../../response-utils.js');
const JsonConfigManager = require('../config/json-config-manager');
const ConfigPathResolver = require('../config/config-path-resolver');
const ServiceManager = require('../integration/service-manager');
const { ErrorFactory } = require('../utils/errors');
const { MCP_TOOLS } = require('../../mcp-tools.js');
const { registerTools } = require('../../mcp-handler.js');

class VisionAnalyzerApplication {
    constructor(options = {}) {
        this.options = {
            projectRoot: options.projectRoot || process.cwd(),
            configManager: options.configManager,
            pathResolver: options.pathResolver,
            webConfigServer: options.webConfigServer,
            serviceManager: options.serviceManager,
            logger: options.logger || console
        };

        this.server = null;
        this.isRunning = false;
        this.startTime = null;
        this.logger = this.options.logger;

        // 调试信息
        if (!this.logger) {
            console.error('WARNING: Logger is undefined in constructor!');
        }
    }

    /**
     * 初始化应用程序
     */
    async initialize() {
        try {
            await this.initializeDependencies();
            await this.initializeConfiguration();

            this.logger.info('Vision Analyzer Application initialized successfully');
            return { success: true };
        } catch (error) {
            if (this.logger) {
                this.logger.error('Failed to initialize application:', error.message);
            } else {
                console.error('Failed to initialize application:', error.message);
            }
            return { success: false, error: error.message };
        }
    }

    /**
     * 初始化依赖项
     */
    async initializeDependencies() {
        // 如果没有提供依赖，则创建默认实例
        if (!this.options.pathResolver) {
            this.options.pathResolver = new ConfigPathResolver();
        }

        if (!this.options.configManager) {
            this.options.configManager = new JsonConfigManager(this.options.projectRoot);
        }

        if (!this.options.webConfigServer) {
            this.options.webConfigServer = new WebConfigServer();
        }

        if (!this.options.serviceManager) {
            this.options.serviceManager = new ServiceManager();
        }

        this.pathResolver = this.options.pathResolver;
        this.configManager = this.options.configManager;
        this.webConfigServer = this.options.webConfigServer;
        this.serviceManager = this.options.serviceManager;
        // 保持原有的logger设置，不要覆盖为undefined
        if (this.options.logger && !this.logger) {
            this.logger = this.options.logger;
        }
    }

    /**
     * 初始化配置
     */
    async initializeConfiguration() {
        const configPathInfo = this.pathResolver.getBestConfigPath(this.options.projectRoot);
        let configLoaded = false;

        if (configPathInfo) {
            this.logger.log(`[Vision Analyzer] 加载配置文件: ${configPathInfo.path} (来源: ${configPathInfo.source})`);
            this.configManager.configPath = configPathInfo.path;
            this.configManager.loadConfig();
            configLoaded = true;
        } else {
            this.logger.warn('[Vision Analyzer] 警告: 未找到配置文件，将创建标准配置');
            this.pathResolver.ensureConfigDir();
            this.configManager.configPath = this.pathResolver.getConfigFilePath();
            this.configManager.createDefaultConfig();
            configLoaded = true;
        }

        this.configLoaded = configLoaded;
        this.configPathInfo = configPathInfo;

        return configLoaded;
    }

    /**
     * 检测运行环境
     */
    detectEnvironment() {
        const isSetupMode = process.argv.includes('setup');
        const configStatus = checkJsonConfiguration(this.getConfigDirectory());

        return {
            isSetupMode,
            configStatus,
            hasValidConfig: configStatus.isValid,
            needsConfiguration: isSetupMode || !configStatus.isValid
        };
    }

    /**
     * 检查是否有可用的API密钥和服务
     */
    async hasWorkingApiServices() {
        try {
            const config = this.configManager.getConfig();
            const status = this.serviceManager.getServiceStatus();

            // 检查是否有有效的提供商配置
            if (!config || !config.providers || Object.keys(config.providers).length === 0) {
                return false;
            }

            // 检查是否有可用的服务
            if (!status.services || !status.providers || status.providers.available === 0) {
                return false;
            }

            // 检查是否有真实的API密钥（不是占位符）
            const hasRealKeys = await this.checkForRealApiKeys(config);
            if (!hasRealKeys) {
                return false;
            }

            return true;
        } catch (error) {
            this.logger.error('检查API服务状态失败:', error.message);
            return false;
        }
    }

    /**
     * 检查是否有真实的API密钥
     */
    async checkForRealApiKeys(config) {
        if (!config.providers) return false;

        for (const [providerName, provider] of Object.entries(config.providers)) {
            if (provider && provider.api_key) {
                // 检查是否是占位符
                const placeholderPatterns = [
                    /your-[^-]+-api-key-here/i,
                    /your-real-[^-]+-key-here/i,
                    /sk-your-real-[^-]+-key-here/i,
                    /YOUR_PROVIDER-YOUR_MODEL/,
                    /your-email@example\.com/,
                    /sk-test-demo-key/i,
                    /test-api-key-demo/i,
                    /sk-your-real-moonshot-key-here/i,
                    /sk-your-real-tencent-key-here/i,
                    /your-real-zhipu-key-here/i
                ];

                const isPlaceholder = placeholderPatterns.some(pattern =>
                    pattern.test(provider.api_key)
                );

                // 如果不是占位符且长度合理，认为是真实密钥
                if (!isPlaceholder && provider.api_key.length > 10) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 获取配置目录
     */
    getConfigDirectory() {
        if (this.configLoaded && this.configPathInfo) {
            return path.dirname(this.configPathInfo.path);
        }
        return this.pathResolver.getConfigDir();
    }

    /**
     * 检查是否只有占位符配置
     */
    async hasOnlyPlaceholderConfig() {
        try {
            const possibleConfigPaths = this.pathResolver.getAllPossiblePaths(this.options.projectRoot);
            const configPath = possibleConfigPaths.find(p => require('fs').existsSync(p));

            if (!configPath) {
                return false;
            }

            const content = require('fs').readFileSync(configPath, 'utf8');
            const meaningfulContent = content.replace(/#.*$/gm, '').trim();

            if (!meaningfulContent) {
                return false;
            }

            const placeholderPatterns = [
                /your-[^-]+-api-key-here/i,
                /your-real-[^-]+-key-here/i,
                /sk-your-real-[^-]+-key-here/i,
                /YOUR_PROVIDER-YOUR_MODEL/,
                /your-email@example\.com/,
                /sk-test-demo-key/i,
                /test-api-key-demo/i,
                /sk-your-real-moonshot-key-here/i,
                /sk-your-real-tencent-key-here/i,
                /your-real-zhipu-key-here/i
            ];

            const hasPlaceholders = placeholderPatterns.some(pattern => pattern.test(content));
            const hasRealApiKey = /api_key["\s]*:\s*["\']([a-zA-Z0-9_\-]{15,})["\']/.test(content) &&
                                 !/your-[^-]+-api-key-here/.test(content) &&
                                 !/your-real-[^-]+-key-here/.test(content) &&
                                 !/test-api-key-demo/.test(content);

            return hasPlaceholders && !hasRealApiKey;
        } catch (error) {
            this.logger.error('检查占位符配置失败:', error.message);
            return false;
        }
    }

    /**
     * 处理配置流程 - 重新设计的行为逻辑
     */
    async handleConfiguration() {
        const env = this.detectEnvironment();

        // 1. 明确的setup模式：强制启动配置界面
        if (env.isSetupMode) {
            return await this.startConfigurationFlow(env);
        }

        // 2. 检查是否有可用的API服务
        const hasWorkingServices = await this.hasWorkingApiServices();

        // 3. 检查是否有待处理的MCP数据（表示这是MCP调用）
        let hasPendingMCPData = false;
        try {
            const fs = require('fs');
            if (process.stdin.fd !== undefined) {
                const stats = fs.fstatSync(process.stdin.fd);
                hasPendingMCPData = stats.size > 0;
            }
        } catch (e) {
            // 忽略错误
        }

        // 4. 根据情况决定启动模式
        if (hasPendingMCPData || process.env.MCP_MODE === '1' || process.argv.includes('--stdio')) {
            // MCP模式：总是启动MCP服务器（根据用户要求，stdio应该是默认行为）
            return await this.startMCPServer();
        } else {
            // 默认模式：根据是否有可用服务决定行为
            if (hasWorkingServices) {
                // 有可用服务，尝试启动HTTP配置服务（可选）
                return await this.tryStartConfigServer(env, hasWorkingServices);
            } else {
                // 没有可用服务，强制启动配置界面
                this.logger.info('🔧 未配置可用的API服务，启动配置界面...');
                return await this.startConfigurationFlow(env);
            }
        }
    }

    /**
     * 尝试启动配置服务器（智能端口冲突处理）
     */
    async tryStartConfigServer(env, hasWorkingServices) {
        try {
            const configDir = this.getConfigDirectory();

            // 尝试启动HTTP服务器
            const serverUrl = await this.webConfigServer.start(configDir, {
                title: 'Vision Analyzer - 配置管理',
                showWelcome: false,
                autoOpen: false, // 不自动打开浏览器
                port: 3000 // 尝试使用固定端口
            });

            this.logger.log('✅ Web配置服务器已启动: ' + serverUrl);
            this.logger.log('💡 配置修改将在下次MCP调用时生效');

            if (hasWorkingServices) {
                this.logger.log('🎯 当前API服务配置可用，MCP服务已就绪');
                return { started: false, mode: 'http_config_ready' };
            } else {
                this.logger.log('🔧 需要配置LLM服务提供商才能使用MCP功能');
                this.logger.log('📝 请访问上述URL完成配置');
                return { started: false, mode: 'http_config_needed' };
            }

        } catch (error) {
            // 端口冲突或其他启动失败
            if (error.message.includes('EADDRINUSE') || error.message.includes('port')) {
                this.logger.log('ℹ️  端口已被占用，跳过HTTP服务启动（其他实例可能正在运行）');
                return { started: false, mode: 'config_complete' };
            } else {
                this.logger.error('HTTP服务启动失败:', error.message);
                return { started: false, mode: 'config_complete' };
            }
        }
    }

    /**
     * 启动配置流程
     */
    async startConfigurationFlow(env) {
        const isPlaceholderConfig = await this.hasOnlyPlaceholderConfig();
        return await this.startConfigServer(isPlaceholderConfig);
    }

    /**
     * 启动配置服务器
     */
    async startConfigServer(isPlaceholderConfig) {
        this.logger.info('🌐 启动Web配置界面...');

        const configDir = this.getConfigDirectory();
        const server = this.webConfigServer;

        const serverUrl = await server.start(configDir, {
            title: isPlaceholderConfig ? 'Vision Analyzer - 配置向导' : 'Vision Analyzer - 配置管理',
            showWelcome: isPlaceholderConfig,
            autoOpen: true,
            port: 0 // 使用随机端口
        });

        this.logger.log('✅ Web配置服务器已启动: ' + serverUrl);
        this.logger.log('📝 请在浏览器中完成LLM服务配置');
        this.logger.log('');

        if (isPlaceholderConfig) {
            this.logger.log('🔧 需要配置LLM服务提供商');
            this.logger.log('═══════════════════════════════════════════════════');
            this.logger.log('🎯 当前配置：');
            this.logger.log('   • 默认服务商: 未知');
            this.logger.log('   • 可用服务商: ');
            this.logger.log('   • MCP 服务器已就绪');
        }

        this.logger.log('💡 配置完成后服务将继续运行');

        try {
            return await this.startPersistentConfigService(server);
        } catch (error) {
            this.logger.error('配置服务启动失败:', error.message);
            throw error;
        }
    }

    /**
     * 启动持久配置服务
     */
    async startPersistentConfigService(webServer) {
        let statusInterval;

        const checkConfig = async () => {
            try {
                const status = this.serviceManager.getServiceStatus();
                const config = this.configManager.getConfig();

                if (this.isValidForMCP(config, status)) {
                    this.logger.log('✅ 配置已验证，准备切换到MCP模式');

                    if (statusInterval) {
                        clearInterval(statusInterval);
                    }

                    await webServer.stop();
                    await this.startMCPServer();

                    return { started: true, mode: 'mcp' };
                }
            } catch (error) {
                this.logger.error('配置检查失败:', error.message);
            }
        };

        statusInterval = setInterval(checkConfig, 10000);
        checkConfig();

        return new Promise((resolve) => {
            this.onConfigComplete = resolve;
        });
    }

    /**
     * 启动MCP服务器
     */
    async startMCPServer() {
        try {
            console.error('[MCP DEBUG] Starting MCP server...');
            this.createMCPServer();
            console.error('[MCP DEBUG] MCP server created, connecting transport...');

            const transport = new StdioServerTransport();
            await this.server.connect(transport);
            console.error('[MCP DEBUG] Transport connected, server ready');

            this.isRunning = true;
            this.startTime = Date.now();

            if (this.logger) {
                this.logger.log('Vision Analyzer MCP Server running on stdio');
            } else {
                console.error('[MCP DEBUG] Vision Analyzer MCP Server running on stdio');
            }

            console.error('[MCP DEBUG] MCP server startup completed successfully');
            return { started: true, mode: 'mcp' };
        } catch (error) {
            console.error('[MCP DEBUG] MCP server startup failed:', error.message);
            console.error('[MCP DEBUG] Error stack:', error.stack);
            if (this.logger) {
                this.logger.error('Failed to start MCP server:', error.message);
            } else {
                console.error('Failed to start MCP server:', error.message);
            }
            throw error;
        }
    }

    /**
     * 创建MCP服务器
     */
    createMCPServer() {
        this.server = new Server(
            {
                name: 'vision-analyzer',
                version: '2.0.5',
            },
            {
                capabilities: {
                    tools: {},
                },
            }
        );

        // 使用完整的MCP工具列表
        this.server.setRequestHandler(ListToolsRequestSchema, async () => {
            const tools = MCP_TOOLS.map(tool => ({
                name: tool.name,
                description: tool.description,
                inputSchema: tool.inputSchema
            }));

            return { tools };
        });

        // 注册工具调用处理器
        this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
            const { name, arguments: args } = request.params;

            const tool = MCP_TOOLS.find(t => t.name === name);
            if (!tool) {
                // 返回错误响应而不是抛出异常
                return {
                    content: [{
                        type: 'text',
                        text: `Unknown tool: ${name}`
                    }]
                };
            }

            try {
                const result = await tool.handler(args);
                return result;
            } catch (error) {
                this.logger.error(`Tool '${name}' failed:`, error.message);
                // 返回错误响应而不是抛出异常
                return {
                    content: [{
                        type: 'text',
                        text: `Tool '${name}' failed: ${error.message}`
                    }]
                };
            }
        });
    }

  
    /**
     * 处理视觉分析器调用
     */
    async handleVisionAnalyzerCall(functionName, ...args) {
        const result = await visionAnalyzer[functionName](...args);
        return result;
    }

    /**
     * 处理配置请求
     */
    async handleConfigRequest(functionName, ...args) {
        switch (functionName) {
            case 'check_config':
                return this.checkConfig();
            case 'get_config_status':
                return this.getConfigStatus();
            case 'list_available_providers':
                return this.listAvailableProviders();
            case 'test_api_connection':
                return await this.testApiConnection(args[0]);
            default:
                throw new Error(`Unknown config tool: ${functionName}`);
        }
    }

    /**
     * 检查配置
     */
    checkConfig() {
        const configStatus = checkJsonConfiguration(this.getConfigDirectory());
        return {
            isValid: configStatus.isValid,
            issues: configStatus.issues || [],
            recommendations: configStatus.recommendations || []
        };
    }

    /**
     * 获取配置状态
     */
    getConfigStatus() {
        try {
            const config = this.configManager.getConfig();
            const status = this.serviceManager.getServiceStatus();

            return {
                config: {
                    version: config.version,
                    current_provider_model: config.current_provider_model,
                    providers_count: Object.keys(config.providers || {}).length
                },
                services: status,
                timestamp: new Date().toISOString()
            };
        } catch (error) {
            return {
                error: error.message,
                config: null,
                services: null,
                timestamp: new Date().toISOString()
            };
        }
    }

    /**
     * 列出可用提供商
     */
    listAvailableProviders() {
        const config = this.configManager.getConfig();
        const providers = [];

        if (config.providers) {
            for (const [name, provider] of Object.entries(config.providers)) {
                if (provider && provider.base) {
                    providers.push({
                        name: name,
                        base: provider.base,
                        models: provider.models || []
                    });
                }
            }
        }

        return {
            providers,
            count: providers.length
        };
    }

    /**
     * 测试API连接
     */
    async testApiConnection(providerName) {
        try {
            const result = await this.serviceManager.testProvider(providerName);
            return {
                provider: providerName,
                success: true,
                response_time_ms: result.response_time_ms,
                message: 'Connection successful'
            };
        } catch (error) {
            return {
                provider: providerName,
                success: false,
                error: error.message,
                message: 'Connection failed'
            };
        }
    }

    /**
     * 检查配置是否适合MCP模式
     */
    isValidForMCP(config, status) {
        return config &&
               config.version &&
               config.current_provider_model &&
               config.providers &&
               Object.keys(config.providers).length > 0 &&
               status.services &&
               status.providers &&
               status.providers.available > 0;
    }

    /**
     * 显示配置成功信息
     */
    showConfigurationSuccess() {
        showConfigurationSuccess();
    }

    /**
     * 运行应用程序
     */
    async run() {
        try {
            // 初始化
            const initResult = await this.initialize();
            if (!initResult.success) {
                throw new Error(`Initialization failed: ${initResult.error}`);
            }

            // 处理配置
            const configResult = await this.handleConfiguration();

            if (configResult.started) {
                if (this.logger) {
                    this.logger.log('Application started successfully');
                }
                return configResult;
            }

            // 检查是否是MCP模式但还没有启动服务器
            if (configResult.mode === 'mcp') {
                return await this.startMCPServer();
            }

            // 如果没有启动服务器，说明配置完成，直接返回
            return { started: false, mode: 'config_complete' };
        } catch (error) {
            if (this.logger) {
                this.logger.error('Application run failed:', error.message);
            } else {
                console.error('Application run failed:', error.message);
                console.error('Logger is undefined, error details:', error);
            }
            throw error;
        }
    }

    /**
     * 停止应用程序
     */
    async stop() {
        try {
            if (this.server && this.isRunning) {
                await this.server.close();
                this.isRunning = false;
                this.server = null;
            }

            if (this.webConfigServer && this.webConfigServer.isRunning) {
                await this.webConfigServer.stop();
            }

            this.isRunning = false;
            this.startTime = null;

            this.logger.info('Application stopped successfully');
            return { success: true };
        } catch (error) {
            this.logger.error('Failed to stop application:', error.message);
            return { success: false, error: error.message };
        }
    }

    /**
     * 获取应用程序状态
     */
    getStatus() {
        return {
            isRunning: this.isRunning,
            startTime: this.startTime,
            uptime: this.isRunning ? Date.now() - this.startTime : 0,
            configLoaded: this.configLoaded,
            configPath: this.configPathInfo?.path || null
        };
    }

    /**
     * 获取配置管理器
     */
    getConfigManager() {
        return this.configManager;
    }

    /**
     * 获取路径解析器
     */
    getPathResolver() {
        return this.pathResolver;
    }

    /**
     * 获取服务管理器
     */
    getServiceManager() {
        return this.serviceManager;
    }
}

module.exports = VisionAnalyzerApplication;